/**
 * 
 */
package com.ctn.bootstarp.tags.ui;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.JspException;

import tldgen.BodyContentType;
import tldgen.Tag;
import tldgen.TagAttribute;

import com.ctn.bootstarp.tags.AppTag;

/**
 * @author weiqi
 * @date 2013年8月7日
 */
@Tag(bodyContentType=BodyContentType.JSP)
public class TabPanelTag extends AppTag {
	
	private static final long serialVersionUID = -6221114197465000794L;
	public static String htmlNavTemp = "<ul class=\"nav nav-tabs\">";
	public static String htmlContentTemp = "<div class=\"tab-content\" style=\"height: {0}px;\">";

	private StringBuffer tabNav = new StringBuffer();
	
	private StringBuffer tabContent = new StringBuffer();
	
	private Integer contentHeight = 300;
	
	private List<TabItem> items = new ArrayList<TabItem>();
	
	public void addItem(TabItem item){
		items.add(item);
	}

	@TagAttribute(description="the tab content height,default:300px")
	public void setContentHeight(Integer contentHeight) {
		this.contentHeight = contentHeight;
	}
	
	@Override
	public int doStartTag() throws JspException {
		return EVAL_BODY_BUFFERED;
	}
	
	@Override
	public void doInitBody() throws JspException {
		tabNav.append(htmlNavTemp);
		tabContent.append(MessageFormat.format(htmlContentTemp, contentHeight));
		super.doInitBody();
	}
	
	
	@Override
	public int doAfterBody() throws JspException {
		for (TabItem item : items) {
			tabNav.append(item.getHtmlHead());
			tabContent.append(item.getHtmlContent());
		}
		tabNav.append("</ul>");
		tabContent.append("</div>");
		return super.doAfterBody();
	}
	
	@Override
	public int doEndTag() throws JspException {
		try {
			pageContext.getOut().write(tabNav.append(tabContent).toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		tabNav.setLength(0);
		tabContent.setLength(0);
		contentHeight = 300;
		items.clear();
		return super.doEndTag();
	}
	
	@Override
	public void release() {
		tabNav=null;
		tabContent=null;
		contentHeight=null;
		items=null;
		super.release();
	}
	
}
